package com.example.lihongxuan.Service;

import com.example.lihongxuan.Control.DBConnection;
import com.example.lihongxuan.Entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Objects;

@WebServlet("/SignupServlet")
public class SignupServlet extends HttpServlet {

    static Connection conn = null;
    static Statement st = null;
    static PreparedStatement ps = null;
    static ResultSet rs= null;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = response.getWriter();
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setUserpassword(request.getParameter("userpassword"));

        if (request.getParameter("userpassword").equals(request.getParameter("suserpassword"))){
            try {
                if (checkAccount(user.getUsername())) {
                    writer.println("该用户名已注册");
                } else{
                    addAccount(user);
                    writer.println("注册成功");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } {

            }
        } else {
            writer.println("前后密码不一致");
        }
    }
    public boolean checkAccount(String username) throws SQLException {
        conn = DBConnection.getConnection();
        String sql = "select userid from lihongxuan.user where username = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1,username);
        rs = ps.executeQuery();
        boolean result = rs.next();
        DBConnection.close(rs,ps,conn);
        return result;
    }
    public void addAccount(User user) throws SQLException{
        conn = DBConnection.getConnection();
        String sql = "insert into lihongxuan.user(username,userpassword) values (?,?)";
        ps = conn.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getUserpassword());
        ps.executeUpdate();
        DBConnection.close(rs,ps,conn);
    }
}
